package com.beichen.service;

import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.aigc.multimodalconversation.OcrOptions;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.beichen.pojo.CertificateInfo;
import com.google.gson.JsonObject;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class AliyunModelService {
    private final Logger logger = LoggerFactory.getLogger(AliyunModelService.class);

    public CertificateInfo recognizeCertificate(String filePath) throws ApiException, NoApiKeyException, UploadFileException {
        System.out.println("=== AliyunModelService.recognizeCertificate ===");
        System.out.println("实际文件路径: " + filePath);
        MultiModalConversation conv = new MultiModalConversation();

        Map<String, Object> imageMap = new HashMap<>();
        imageMap.put("image", filePath);
        imageMap.put("max_pixels", "6422528");
        imageMap.put("min_pixels", "3136");
        imageMap.put("enable_rotate", true);

        System.out.println("构建的图像消息: " + imageMap);

        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(
                        imageMap,
                        Collections.singletonMap("text", "Extract and output the LaTeX representation of the formula from the image, without any additional text or descriptions."))).build();
        JsonObject resultSchema = new JsonObject();
        resultSchema.addProperty("student", "");
        resultSchema.addProperty("teacher", "");
        resultSchema.addProperty("competition", "");
        resultSchema.addProperty("enterprise", "");
        resultSchema.addProperty("number", "");
        resultSchema.addProperty("date", "");

        OcrOptions ocrOptions = OcrOptions.builder()
                .task(OcrOptions.Task.KEY_INFORMATION_EXTRACTION)
                .taskConfig(OcrOptions.TaskConfig.builder()
                        .resultSchema(resultSchema)
                        .build())
                .build();

        MultiModalConversationParam param = MultiModalConversationParam.builder()
                .apiKey("sk-655c120c968f4280be1ecb18a10bed03")
                .model("qwen-vl-ocr-latest")
                .message(userMessage)
                .ocrOptions(ocrOptions)
                .build();
        MultiModalConversationResult result = conv.call(param);
        System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("ocr_result"));

        try {
            logger.info("阿里云模型调用成功，结果: " + result);

            // 提取识别结果并封装到 CertificateInfo 对象中
            CertificateInfo certificateInfo = new CertificateInfo();

            Map<String, Object> ocrResult = (Map<String, Object>) result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("ocr_result");
            Map<String, Object> kvResult = (Map<String, Object>) ocrResult.get("kv_result");

            certificateInfo.setStudent((String) kvResult.get("student"));
            certificateInfo.setTeacher((String) kvResult.get("teacher"));
            certificateInfo.setCompetition((String) kvResult.get("competition"));
            certificateInfo.setEnterprise((String) kvResult.get("enterprise"));
            certificateInfo.setNumber((String) kvResult.get("number"));
            certificateInfo.setDate((String) kvResult.get("date"));
            return certificateInfo;

        } catch (ApiException e) {
            System.err.println("阿里云模型调用失败: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }
}
